/**
 *
 */
package cn.hg.jfsa.manage.controller.module.goods;

import cn.hg.base.jfinal.controller.BaseController;
import cn.hg.base.kit.StrExtKit;
import cn.hg.jfsa.core.SessionThreadLocal;
import cn.hg.jfsa.manage.controller.module.goods.validator.GoodsValidator;
import cn.hg.jfsa.manage.service.GoodsService;
import cn.hg.jfsa.manage.web.LayuiPage;
import cn.hg.jfsa.model.Goods;
import cn.hg.jfsa.model.GoodsImage;
import cn.hg.jfsa.model.JfsaAdmin;
import cn.hg.jfsa.web.theme.ThemeManager;
import com.jfinal.aop.Before;
import com.jfinal.aop.Inject;
import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.SqlPara;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.plugin.ehcache.CacheInterceptor;
import com.jfinal.plugin.ehcache.CacheName;
import com.jfinal.plugin.ehcache.EvictInterceptor;

import java.sql.SQLException;
import java.util.Date;
import java.util.Random;

/**
 * @author Golly
 *
 */
public class GoodsController extends BaseController {

	/**
	 * 商品服务
	 */
	@Inject
	public static GoodsService goodsService;

	/**
	 * 跳转到列表页面
	 */
	@Before(CacheInterceptor.class)
	@CacheName("goods")
	public void index() {
		//this.setAttr("goodsCategoryList", goodsService.getGoodsCategoryAll());
	}

	/**
	 * Ajax方式查询
	 */
	@Before(CacheInterceptor.class)
	@CacheName("goods")
	public void ajaxSearch() {
		// 建立查询键值对
		Kv para = Kv.by("name", this.getPara("name"))
				.set("style", this.getPara("style"))
				.set("status", this.getPara("status"))
				.set("sortField", StrExtKit.humpToUnderline(this.getPara("sortField")))
				.set("sortType", this.getPara("sortType"))
				.set("theme", ThemeManager.me().getCurrentTheme().getId());

		// 通过SQL模板引擎构建SQL及参数
		SqlPara sqlPara = Db.getSqlPara("module.findGoods", para);

		// 执行查询
		Page<Goods> page = Goods.DAO.paginate(getParaToInt("page"), getParaToInt("limit"), sqlPara);

		// 返回Ajax调用的Json结果
		this.renderJson(new LayuiPage(page));
	}

	/**
	 * 跳转到新增页面
	 */
	public void add() {
		//this.setAttr("goodsCategoryList", goodsService.getGoodsCategoryAll());
		//this.setAttr("specItemList", goodsService.getSpecItemAll());
		//this.setAttr("imgPlaceDict", dictService.getDictsByParentCode(GOODS_IMG_PLACE_TYPE_DICT_CODE));
		Goods bean = new Goods();
		bean.setStatus("off").setBaseHits(Math.abs(new Random().nextInt() % 1000)).setHits(0);
		this.setAttr("goods", bean);
	}

	/**
	 * 跳转到编辑商品基本页面
	 */
	public void edit() {
		//this.setAttr("goodsCategoryList", goodsService.getGoodsCategoryAll());
		//this.setAttr("specItemList", goodsService.getSpecItemAll());
		//this.setAttr("imgPlaceDict", dictService.getDictsByParentCode(GOODS_IMG_PLACE_TYPE_DICT_CODE));
		// 根据ID查找到Bean
		this.setAttr("goods", Goods.DAO.findById(this.getParaToInt("id")));
	}

	/**
	 * 跳转到编辑商品图片及布局页面
	 */
	public void editLayout() {
		// 根据ID查找到Bean
		this.setAttr("goods", Goods.DAO.findById(this.getParaToInt("id")));
	}

	@Before(EvictInterceptor.class)
	@CacheName("goods")
	public void updateLayout() {
		// editGoodsImageIds[]={24,18,16,17,19,21,22,20,23}      商品图片ID表
		// editGoodsImagePlaceIds[]={21,16,16,19,17,17,17,20,21} 图片位置ID表
		// editGoodsImageSortNums[]={0,1,2,1,1,2,3,1,1}          商品图片排序表
//		Integer goodsId = this.getParaToInt("goods.id");
//		Goods goods = Goods.dao.findById(goodsId);
//
//		List<GoodsImagePlace> placeList = goods.getGoodsImagePlaceList();
//
//		Integer[] goodsImageIds = this.getParaValuesToInt("editGoodsImageIds");
//		Integer[] editGoodsImagePlaceIds = this.getParaValuesToInt("editGoodsImagePlaceIds");
//		Integer[] goodsImageSortNums = this.getParaValuesToInt("editGoodsImageSortNums");
//
//		if(goodsImageIds != null) {
//			for(int i = 0; i < goodsImageIds.length; i++) {
//				GoodsImage image = GoodsImage.dao.findById(goodsImageIds[i]);
//
//				if(null != image && placeList.size() > 0) {
//					for(GoodsImagePlace place : placeList) {
//						if(place.getId() == editGoodsImagePlaceIds[i]) {
//							image.setPlaceId(place.getId()).setPlaceCode(place.getCode())
//									.setSortNum(goodsImageSortNums[i]).update();
//							break;
//						}
//					}
//				}
//			}
//		}
//
//		this.redirect("/admin/goods/editLayout?id=" + goodsId);
	}

	@Before({GoodsValidator.class, Tx.class, EvictInterceptor.class})
	@CacheName("goods")
	public void saveOrUpdate() {
		// 获取页面传入的Bean
		Goods bean = this.getBean(Goods.class, "goods");

		JfsaAdmin user = SessionThreadLocal.getAdmin();

		Integer id = bean.getId();

		if (null == id) {
			// 新建记录
			bean.setCreatorId(user.getId()).setCreatedTime(new Date()).setEditorId(user.getId()).setEditedTime(new Date());
			id = bean.getId();
		}
		// 更新记录
		bean.setEditorId(user.getId()).setEditedTime(new Date()).update();

		// 主记录完成后，处理关联数据
		this.updateGoodsSpecs(bean);
		this.updateGoodsImagePlaces(bean);

		// 生成商品规格字串
		genSpecStr(bean);

		this.redirect("/admin/goods/edit?id=" + id);
	}

	/**
	 * 生成商品规格字串
	 * @param bean
	 */
	private void genSpecStr(Goods bean) {
//		List<GoodsSpec> specList = bean.getGoodsSpecList();
//		StringBuilder sb = new StringBuilder();
//		for(GoodsSpec goodsSpec : specList) {
//			sb.append("<p>").append(goodsSpec.getSpecItemName()).append(" ： ").append(goodsSpec.getSpecItemValue()).append("</P>");
//		}
//		bean.setSpecStr(sb.toString());
//
//		bean.update();
	}

	/**
	 * @param bean
	 */
	private void updateGoodsSpecs(Goods bean) {
		// editSpecTypes[]={old,old,old,del,new}
		// editGoodsSpecIds[]={1,2,3,5,}
		// editSpecIds[]={1,2,3,2,3}
		// editSpecValues[]={纸盒,36%,1件,删除测试,追加的}
		// editSpecSortNums[]={1,2,3,99,4}

//		String[] specTypes = this.getParaValues("editSpecTypes"); // 编辑类型
//		Integer[] goodsSpecIds = this.getParaValuesToInt("editGoodsSpecIds"); // 原记录中的placeID
//		Integer[] specIds = this.getParaValuesToInt("editSpecIds"); // 对应specItem的ID
//		String[] specValues = this.getParaValues("editSpecValues");
//		Integer[] specSortNums = this.getParaValuesToInt("editSpecSortNums");
//
//		if(specTypes == null) {
//			return;
//		}
//
//		List<SpecItem> specItemList = goodsService.getSpecItemAll();
//
//		for(int i = 0; i < specTypes.length; i++) {
//			switch (specTypes[i]) {
//			case "new":
//				for(SpecItem specItem : specItemList) {
//					if(specItem.getId() == specIds[i]) {
//						new GoodsSpec().setTheme(ThemeManager.me().getCurrentTheme().getId()).setGoodsId(bean.getId()).setSpecItemId(specItem.getId())
//								.setSpecItemName(specItem.getName()).setSpecItemValue(specValues[i])
//								.setSortNum(specSortNums[i]).save();
//						break;
//					}
//				}
//				break;
//			case "old":
//				GoodsSpec oldSpec = GoodsSpec.dao.findById(goodsSpecIds[i]);
//				if(null == oldSpec) break;
//
//				for(SpecItem specItem : specItemList) {
//					if(specItem.getId() == specIds[i]) {
//						oldSpec.setSpecItemId(specItem.getId()).setSpecItemName(specItem.getName())
//								.setSpecItemValue(specValues[i]).setSortNum(specSortNums[i]).update();
//						break;
//					}
//				}
//				break;
//			case "del":
//				GoodsSpec delSpec = GoodsSpec.dao.findById(goodsSpecIds[i]);
//				if(null != delSpec) delSpec.delete();
//
//				break;
//
//			default:
//				break;
//			}
//		}
	}

	/**
	 * 动态处理商品图片布局
	 * @param bean
	 */
	private void updateGoodsImagePlaces(Goods bean) {
		// editImagePlaceTypes[]={old,old,old,old,del,new}
		// editGoodsPlaceIds[]={5,6,7,8,11,}
		// editImagePlaceIds[]={30,31,32,33,30,30}
		// editImagePlaceSortNums[]={1,2,3,5,99,6}
//		String[] imagePlaceTypes = this.getParaValues("editImagePlaceTypes"); // 编辑类型
//		Integer[] goodsPlaceIds = this.getParaValuesToInt("editGoodsPlaceIds"); // 原记录中的placeID
//		Integer[] imagePlaceIds = this.getParaValuesToInt("editImagePlaceIds"); // 对应的字典ID
//		Integer[] imagePlaceSortNums = this.getParaValuesToInt("editImagePlaceSortNums"); // 记录排序值
//
//		if(imagePlaceTypes == null) {
//			return;
//		}
//
//		List<SysDict> sysDictList = dictService.getDictsByParentCode(GOODS_IMG_PLACE_TYPE_DICT_CODE);
//
//		for(int i = 0; i < imagePlaceTypes.length; i++) {
//			switch (imagePlaceTypes[i]) {
//			case "new":
//				for(SysDict dict : sysDictList) {
//					if(dict.getId().equals(imagePlaceIds[i])) {
//						new GoodsImagePlace().setTheme(ThemeManager.me().getCurrentTheme().getId()).setGoodsId(bean.getId()).setCode(dict.getValue()).setName(dict.getName())
//								.setSortNum(imagePlaceSortNums[i]).save();
//						break;
//					}
//				}
//				break;
//			case "old":
//				GoodsImagePlace oldPlace = GoodsImagePlace.dao.findById(goodsPlaceIds[i]);
//				if(null == oldPlace) break;
//
//				for(SysDict dict : sysDictList) {
//					if(dict.getId().equals(imagePlaceIds[i])) {
//						oldPlace.setCode(dict.getValue()).setName(dict.getName()).setSortNum(imagePlaceSortNums[i]).update();
//						break;
//					}
//				}
//				break;
//			case "del":
//				GoodsImagePlace delPlace = GoodsImagePlace.dao.findById(goodsPlaceIds[i]);
//				if(null != delPlace) delPlace.delete();
//
//				break;
//
//			default:
//				break;
//			}
//		}
	}

	/**
	 * Ajax删除功能
	 */
	@Before(EvictInterceptor.class)
	@CacheName("goods")
	public void ajaxDel() {
		// 通过页面传入的ID查找到记录
		Goods bean = Goods.DAO.findById(this.getParaToInt("id"));

		// 记录不存在则报错
		if (null == bean) {
			this.renderAjaxFailed("1", "记录不存在！");
			return;
		}

		// 更新记录的状态为删除
		bean.setStatus("del").update();

		// 返回Ajax成功
		this.renderAjaxSuccessed();
	}


	/**
	 *
	 */
	@Before(EvictInterceptor.class)
	@CacheName("goods")
	public void ajaxAddGoodsImage() {
		Integer goodsId = this.getParaToInt("goodsId");
		String img = this.getPara("img");
		String thumb = this.getPara("thumb");

		// 这里引用事务处理是为了方便Ajax模式处理
		Db.tx(new IAtom() {
			public boolean run() throws SQLException {
				new GoodsImage().setTheme(ThemeManager.me().getCurrentTheme().getId())
						.setGoodsId(goodsId)
						.setImg(img)
						.setThumb(thumb)
						.save();
				return true;
			}
		});

		// 返回Ajax成功
		this.renderAjaxSuccessed();
	}

	@Before(EvictInterceptor.class)
	@CacheName("goods")
	public void ajaxDelGoodsImage() {
		Integer id = this.getParaToInt("id");

		GoodsImage.DAO.deleteById(id);

		this.renderAjaxSuccessed();
	}

	@Before(CacheInterceptor.class)
	@CacheName("goods")
	public void view() {

	}
}
